package com.util.zyncroweb;

import java.lang.reflect.Type;
import java.util.Map;

import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Verb;

import com.api.services.IZyncroApi;
import com.api.test.Api;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class ZyncroWebApi {

	private String sessionUrn;

	private final Api serviceApi;

	private final String hostUrl;

	public ZyncroWebApi(Api serviceApi, String hostUrl) {
		this.serviceApi = serviceApi;
		this.hostUrl = hostUrl;
	}

	public String login(String username, String password) {
		Map<String, String> result = serviceApi.getService(IZyncroApi.class).login(username, password);
		this.sessionUrn = result.get("stringResult");
		return sessionUrn;
	}

	public String getSessionUrn() {
		if (sessionUrn == null) {
			throw new IllegalStateException("SessionUrn is null - user is not logged in");
		}
		return sessionUrn;
	}

	public void editDomainProperty(String urnDomain, DomainProperty property, EnumId valueId) {

		String editDomainPropertiesPath = "/userservice/domain/editProperties";

		String sessionUrn = getSessionUrn();

		OAuthRequest request = new OAuthRequest(Verb.POST, hostUrl + editDomainPropertiesPath);
		request.addBodyParameter("sessionUrn", sessionUrn);
		request.addBodyParameter("urnDomain", urnDomain);
		request.addBodyParameter("listProperties", String.valueOf(property.getId()));
		request.addBodyParameter("listProperties", String.valueOf(valueId.getId()));

		Response response = request.send();

		if (isWebResultException(response)) {
			throw new IllegalStateException(String.format("Couldn't edit domain property [urnDomain: %s, property: %s, valueId: %s] - %s",
					urnDomain, property, valueId, response.getBody()));
		}
	}

	public void setUserStatus(UserStatus status, String message) {
		String sessionUrn = getSessionUrn();
		serviceApi.getService(IZyncroApi.class).setUserStatus(sessionUrn, status.getId(), message);
	}

	public Api getServiceApi() {
		return this.serviceApi;
	}

	private boolean isWebResultException(Response response) {
		Type type = new TypeToken<Map<String, String>>() {
		}.getType();
		Map<String, String> resultValues = new Gson().fromJson(response.getBody(), type);
		return resultValues.get("result").equals("FAIL");
	}
}
